// ignore_for_file: file_names

import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'dart:ui' as ui;

import 'package:flutter/services.dart';

class Utils {
    ///输入设置高度，根据原始图片尺寸计算宽度
    static double calcWidth(double inputHeight, double fixWidth, double fixHeight) {
        return (inputHeight * fixWidth / fixHeight);
    }
    ///输入设置宽度，根据原始图片尺寸计算高度
    static double calcHeight(double inputWidth, double fixWidth, double fixHeight) {
        return (inputWidth * fixHeight / fixWidth);
    }
    static double getHeight(BuildContext context) {
        return MediaQuery.of(context).size.height;
    }
    static double getWidth(BuildContext context) {
        return MediaQuery.of(context).size.width;
    }
    static Future<ui.Image> loadImageByAssets(AssetImage assetImage) async {
        Completer<ui.Image> completer = Completer();
        ImageStream imageStream = assetImage.resolve(ImageConfiguration.empty);
        late ImageStreamListener listener;
        listener = ImageStreamListener((ImageInfo info, bool synchronousCall) {
            final ui.Image img = info.image;
            completer.complete(img);
            imageStream.removeListener(listener);
        });
        imageStream.addListener(listener);
        return completer.future;
    }
    // 获取本地图片  返回ui.Image 需要传入BuildContext context
    static Future<ui.Image> loadImageByAssets2(String asset, BuildContext context, {width, height}) async {
        ByteData data = await DefaultAssetBundle.of(context).load(asset);
        ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
            targetWidth: width, targetHeight: height);
        ui.FrameInfo fi = await codec.getNextFrame();
        return fi.image;
    }

    // 获取本地图片 返回ui.Image 不需要传入BuildContext context
    static Future<ui.Image> loadImageByAssets3(String asset, {width, height}) async {
        ByteData data = await rootBundle.load(asset);
        ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
            targetWidth: width, targetHeight: height);
        ui.FrameInfo fi = await codec.getNextFrame();
        return fi.image;
    }
    // 计算文本宽度和高度
    static Size boundingTextSize(BuildContext context, String text, TextStyle style,  {int maxLines = 2^31, double maxWidth = double.infinity}) {
        if (text.isEmpty) {
            return Size.zero;
        }
        final TextPainter textPainter = TextPainter(
            textDirection: TextDirection.ltr,
            locale: Localizations.localeOf(context),
            text: TextSpan(text: text, style: style), maxLines: maxLines)
            ..layout(maxWidth: maxWidth);
        return textPainter.size;
    }
    static Future<String> readJson(String jsonFileName) async {
        return await rootBundle.loadString('assets/data/$jsonFileName');
    }
}
